<template>
  <view class="main-header">
    <text>{{ name }}</text>
  </view>
  <view class="main-pingfen">
    <view class="identifylabelids-button">
      <view class="identifylabelids-button-item">
        <uv-button :custom-style="miniButton" :color="yellow_selected === id ? '#748ee2' : '#aaaaaa'" text="概览"
          @click="yellow_selected = id">
        </uv-button>
      </view>
      <view v-for="(v, i) in yellowlist" :key="i" class="identifylabelids-button-item">
        <uv-button :custom-style="miniButton" :color="yellow_selected === v.id ? '#748ee2' : '#aaaaaa'" :text="v?.name"
          @click="yellow_selected = String(v.id)"></uv-button>
      </view>
    </view>
  </view>
  <view class="container">
    <slot class="container" :show="show && showyellow" id="mychart-dom-yellow" canvasId="mychart-yellow"
      :ec="{ onInit: (canvas: any, width: string | number, height: string | number, dpr: number) => setyellow(canvas, width, height, dpr) }">
    </slot>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, shallowRef, watch } from "vue";
import { miniButton } from "@/util/style";
import { nextTick } from "vue";
//@ts-ignore
const echarts = require("../../wxcomponents/ec-canvas/echarts");
import { getchildrenlast, getTreeDepth } from "@/util";
import { useI18n } from "vue-i18n";
import { onUnload } from "@dcloudio/uni-app";

interface Idata {
  dept_id: string;
  name: string;
  count: string;
  aiidentifylabelid: string;
  release: string;
}
type Ip = {
  list: Eps.aiidentifylabelEntity[];
  id?: string;
  identifycommentlabelcount: Idata[];
  name: string;
  type: 0 | 1 | true;
  show?: boolean;
};
const $t = useI18n().t;
const p = withDefaults(defineProps<Ip>(), {
  list: () => [],
});

const showyellow = ref(true);
const yellow_identifycommentlabels = ref<string[]>([]);

onMounted(() => {
  if (p.id) {
    yellow_selected.value = p.id;
  }
});

const yellow_selected = ref<string>();

const yellowlist = computed(() => {
  const data = p.list
    .filter((c) => String(c.parentId) == p.id)
    .sort((a, b) => Number(a.orderNum) - Number(b.orderNum));
  const deep = getTreeDepth(data);
  if (deep < 2) {
    return [];
  }
  return data;
});

const chart = shallowRef();

function setyellow(
  canvas: any,
  width: string | number,
  height: string | number,
  dpr: number
) {
  chart.value = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, // new
  });

  chart.value.setOption(setoption(), { notMerge: true });
  canvas.setChart(chart.value);
  chart.value.on("click", click);
  return chart.value;
}

onUnload(() => {
  chart.value.off("click"); // 移除 click 事件监听
});

const emits = defineEmits(["click1"]);
function click(e: any) {
  const n = p.list.find(
    (z) => z.parentId === yellow_selected.value && z.name === e.name
  );
  if (n?.children?.length) {
    yellow_selected.value = String(n.id);
  } else {
    emits("click1", e, yellow_selected.value);
  }
}

function setoption() {
  const option: Record<string, any> = {
    color: [
      "#FD754C",
      "#cccccc",
      "#ee5253",
      "#5f27cd",
      "#10ac84",
      "#feca57",
      "#f368e0",
      "#00d2d3",
      "#341f97",
      "#576574",
    ],
    legend: {
      top: "top",
      left: "left",
      data: ["当前周期", "上一周期"],
      selected: {
        "上一周期": false  // 将 "Lowest" 设置为默认不选中
      }
    },
    title: false,
    tooltip: {
      trigger: "item",
      formatter: "{b} : {c} ",
    },
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "当前周期",
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
      },
      {
        name: "上一周期",
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
        sort: "descending",
      },
    ],
  };
  if (p.list) {
    yellow_identifycommentlabels.value =
      p.list
        .find((c) => String(c.id) === yellow_selected.value)
        ?.children?.filter((c: any) => true === p.type || c.type === p.type) ||
      [];

    // 截取前10条数据
    option.xAxis.data = yellow_identifycommentlabels.value
      .map((e: any) => e.name)
      .slice(0, 10);

    const _list =
      p.list
        ?.find((c) => c.id == yellow_selected.value)
        ?.children?.filter((c: any) => true === p.type || c.type == p.type)
        .map((c: any) => {
          return getSubsetCounts([c], c.id);
        }).slice(0, 10) || [];


    // 使用 slice(0, 10) 截取前10条数据
    option.series = [
      {
        name: "当前周期",
        type: "bar",
        data: _list.map((e: any) => e.Ncount),
        markArea: null,
        sort: "descending",
        realtimeSort: true,
        label: {
          show: true,
          position: "top",
        },
      },
      {
        name: "上一周期",
        type: "bar",
        data: _list.map((e: any) => e.Ocount),
        label: {
          show: true,
          formatter: (value: any) => {
            if (value.value) {
              return value.name.split("").join("\n")
            }
            return "";
          },
          verticalAlign: "bottom",
          align: "left",
          position: "bottom",
          distance: -10,
          offset: [-5, 0],
          textBorderWidth: 0,
          textShadowBlur: 0,
        },
      },
    ];
  }

  return option;
}


watch(
  () => p.id,
  () => {
    yellow_selected.value = p.id;
  }
);

watch(
  () => yellow_selected.value,
  () => {
    if (!yellow_selected.value) return;
    // yellow_selected.value = p.id;

    nextTick(() => {
      chart.value?.setOption(setoption(), { notMerge: true });
    });
  }
);
interface I {
  id: string;
  create_time: string;
  update_time: string;
  name: string;
  orderNum: number;
  remark: null;
  parentId: null;
  tenant_id: string;
  type: 0;
  Ncount?: string;
  Ocount?: string;
  children?: I[];
}
function getSubsetCounts(
  tree: I[],
  id: string
): { Ncount: number; Ocount: number } | null {
  for (const node of tree) {
    if (node.id === id) {
      let totalNcount = node.Ncount ? parseInt(node.Ncount) : 0;
      let totalOcount = node.Ocount ? parseInt(node.Ocount) : 0;
      if (node.children) {
        for (const child of node.children) {
          const childCounts = getSubsetCounts(node.children, child.id);
          if (childCounts) {
            totalNcount += childCounts.Ncount;
            totalOcount += childCounts.Ocount;
          }
        }
      }

      return { Ncount: totalNcount, Ocount: totalOcount };
    } else {
      if (node.children) {
        const childCounts = getSubsetCounts(node.children, id);
        if (childCounts) {
          return childCounts;
        }
      }
    }
  }

  return null; // 如果没有找到
}
</script>
